package org.gdpu.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.sun.net.httpserver.Authenticator;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.Service.StudentService;
import org.gdpu.model.Student;
import org.gdpu.util.ChangeTime;
import org.gdpu.util.ExcelUtil;
import org.gdpu.vo.FileVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 14-3-20.
 */
@Component("fileDownload")
@Scope("prototype")
public class FileDownloadAction extends ActionSupport implements ModelDriven<FileVO> {
    @Qualifier("excelUtil")
    @Autowired
    private ExcelUtil excelUtil;
    private final static Logger logger = LogManager.getLogger(FileDownloadAction.class);
    private StudentService studentService;
    private final FileVO fileVO = new FileVO();
    private static String SAVE_PATH_DIR = "D:/Dormitory/_file/_excel/_student/";
    private static String TEMPLATE_PATH_DIR = "D:/Dormitory/_file/_template/";
    private static String INFORMATION_PATH_DIR = "D:/Dormitory/_file/_information/";
    private static Process process;//执行子进程

    //返回一个输入流，作为一个客户端来说是一个输入流，但对于服务器端是一个 输出流
    public InputStream getDownloadFile() throws Exception  {
        fileVO.setFileName(new String(fileVO.getFileName().getBytes(), "ISO8859-1"));
        File file = new File(fileVO.getFilePath());
        if (file.exists())
            return new FileInputStream(file);
        else {
            fileVO.setResultMessage("浏览器不支持，请更换浏览器！");
            return null;
        }
    }

    //TODO:主页初始化通知文件，方法已写好
    public String show() {
        File file = new File(INFORMATION_PATH_DIR);
        String[] list = file.list();
        for(String s :list){
            List<String> sts = new ArrayList<String>();
            sts.add(s.substring(0,10));
            sts.add(s.substring(10));
            fileVO.getInformation().add(sts);
        }
        return "index";
    }

    public String download() throws Exception{
        return SUCCESS;
    }

    public String downloadByBuilding() throws Exception{
        // 得到下载文件文件的目录的真实路径
        File dir = new File(SAVE_PATH_DIR);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        if (fileVO.getCampus().isEmpty()) {
            fileVO.setResultMessage("<script>alert('请选择校区！');location.href='/page/searchManagement/findDormitoryByBuilding.jsp';</script>");
            return ERROR;
        }

        if (fileVO.getBuilding().isEmpty()) {
            fileVO.setResultMessage("<script>alert('请选择宿舍楼！');location.href='/page/searchManagement/findDormitoryByBuilding.jsp';</script>");
            return ERROR;
        }
        List<Student> sts = studentService.findStudent("building", fileVO.getBuilding() + fileVO.getCampus());
        if(sts.isEmpty()){
            fileVO.setResultMessage("<script>alert('没有数据，请重新选择！');location.href='/page/searchManagement/findDormitoryByBuilding.jsp';</script>");
            return ERROR;
        }
        String fileName = ChangeTime.formatDate(ChangeTime.getCurrentDate()) + ".xlsx";
        excelUtil.exportExcelByPath(SAVE_PATH_DIR + fileName, sts, Student.class, true, fileVO.getBuilding() + "栋 学生宿舍信息（"+fileVO.getCampus()+"）");
        fileVO.setFilePath(SAVE_PATH_DIR + fileName);
        fileVO.setFileName(fileName);
        logger.trace(" download students records success,file name is " + fileName);
        return SUCCESS;
    }

    public String execute() throws Exception{
        List<Student> sts = new ArrayList<Student>();

        if (fileVO.getCampus().isEmpty()) {
            fileVO.setResultMessage("<script>alert('请选择校区！');location.href='/page/searchManagement/findDormitoryByCampus.jsp';</script>");
            return ERROR;
        }

        else if (fileVO.getCollege().isEmpty()) {
            fileVO.setResultMessage("<script>alert('请选择学院！');location.href='/page/searchManagement/findDormitoryByCampus.jsp';</script>");
            return ERROR;
        }

        else if (fileVO.getMajor().isEmpty())
            sts = studentService.findStudent("college", fileVO.getCollege());
        else
            sts = studentService.findStudent("major", fileVO.getMajor());
        if(sts.isEmpty()){
            fileVO.setResultMessage("<script>alert('没有数据，请重新选择！');location.href='/page/searchManagement/findDormitoryByCampus.jsp';</script>");
            return ERROR;
        }
        // 得到下载文件目录的真实路径
        File dir = new File(SAVE_PATH_DIR);
        // 如果该目录不存在，就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String fileName = ChangeTime.formatDate(ChangeTime.getCurrentDate()) + ".xlsx";
        if(fileVO.getMajor().isEmpty())
            excelUtil.exportExcelByPath(SAVE_PATH_DIR + fileName, sts, Student.class, true, sts.get(0).getMajor().getCollege().getCollegeName()+ " 学生宿舍信息（"+fileVO.getCampus()+"）");
        else
            excelUtil.exportExcelByPath(SAVE_PATH_DIR + fileName, sts, Student.class, true, sts.get(0).getMajor().getMajorName() + " 学生宿舍信息（"+fileVO.getCampus()+"）");
        fileVO.setFilePath(SAVE_PATH_DIR + fileName);
        fileVO.setFileName(fileName);
        logger.trace(" download students records success,file name is " + fileName);
        return SUCCESS;
    }

    public String getFileList() throws Exception{
        File file = new File(TEMPLATE_PATH_DIR);
        String[] list = file.list();
        for(String s :list)
            fileVO.getFileList().add(s);
        return "view";
    }

    @Resource(name = "studentServiceImpl")
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }


    @Override
    public FileVO getModel() {
        return fileVO;
    }
}
